package com.sjsu.cloudmanager.client.ui;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.*;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sjsu.cloudmanager.client.CloudManager;
import com.sjsu.cloudmanager.client.LabManagerEvents;
import com.sjsu.cloudmanager.client.service.CloudUserAdminServiceAsync;
import com.sjsu.cloudmanager.client.ui.model.CloudUserBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ckempaiah
 * Date: 10/21/11
 * Time: 9:16 AM
 * To change this template use File | Settings | File Templates.
 */
public class LabUserMainPanel extends LayoutContainer {

    private ListStore<ModelData> gridStore;
    private LabUserFormPanel labUserFormPanel;
    private Grid userGrid;

    @Override
    protected void onRender(Element parent, int index) {
        super.onRender(parent, index);
        ContentPanel cp = new ContentPanel();
        //cp.setBorders(true);
        //cp.setStyleAttribute("margin", "0px 0px 5px 0");
        //setStyleAttribute("margin", "10px");

        cp.setFrame(true);
        cp.setHeight(650);
        cp.setHeaderVisible(false);
        cp.setLayout(new RowLayout(Style.Orientation.VERTICAL));

        List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

        CheckBoxSelectionModel<ModelData> checkBoxSelectionModel = new CheckBoxSelectionModel<ModelData>();

        configs.addAll(Arrays.asList(new ColumnConfig[]{
                checkBoxSelectionModel.getColumn(),
                new ColumnConfig("userId", "", 100),
                new ColumnConfig("userName", "User Id", 150),
                new ColumnConfig("userFirstName", "First Name", 100),
                new ColumnConfig("userLastName", "Last Name", 150),
                new ColumnConfig("userEmail", "Email", 150),
                new ColumnConfig("userCreatedDate", "Created Date", 100),
                new ColumnConfig("userUpdatedDate", "Updated Date", 100)

        }));
        configs.get(1).setHidden(true);
        BaseListLoader<BaseListLoadResult<ModelData>> loader = getLoader();
        ListStore<ModelData> store = new ListStore<ModelData>(loader);
        store.setMonitorChanges(true);
        //store.add(getLabInfo());
        gridStore = store;
        ColumnModel cm = new ColumnModel(configs);

        Grid<ModelData> grid = new Grid<ModelData>(store, cm);
        grid.getView().setEmptyText("Empty");
        grid.setBorders(false);
        //grid.setAutoExpandColumn("labName");
        grid.setSelectionModel(checkBoxSelectionModel);
        //grid.addPlugin(checkBoxSelectionModel);
        this.userGrid = grid;
        cp.add(grid, new RowData(1, 0.5));

        //cp.add(lrp, new RowData(.5, .5));
        ToolBar toolBar = new ToolBar();
        toolBar.setBorders(false);


        toolBar.setAlignment(Style.HorizontalAlignment.LEFT);
        toolBar.add(new Button("Add", new SelectionListener<ButtonEvent>() {
            public void componentSelected(ButtonEvent ce) {
                if (labUserFormPanel == null) {

                    labUserFormPanel = new LabUserFormPanel();
                }
                labUserFormPanel.show();
                labUserFormPanel.getFormBinding().clear();
                labUserFormPanel.getFormBinding().bind(new CloudUserBean());
                //labResourceFormPanel.fireEvent(LabManagerEvents.AddMachine, baseEvent);
            }
        }));


        ToolbarAction.getInstance().addListener(LabManagerEvents.SaveUser, new Listener<BaseEvent>() {
            @Override
            public void handleEvent(BaseEvent be) {
                gridStore.getLoader().load();
            }
        });
        toolBar.add(getEditButton());


        toolBar.add(getDeleteButton());
        cp.setTopComponent(toolBar);
        add(cp);

        grid.addListener(Events.Render, new Listener<GridEvent<ModelData>>() {
            @Override
            public void handleEvent(GridEvent<ModelData> modelDataGridEvent) {
                gridStore.getLoader().load();
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });
        setLayout(new FitLayout());
    }

    private Button getEditButton() {
        Button button = new Button("Edit", new SelectionListener<ButtonEvent>() {
            public void componentSelected(ButtonEvent ce) {
                if (labUserFormPanel == null) {

                    labUserFormPanel = new LabUserFormPanel();
                }
                labUserFormPanel.show();
                if (userGrid.getSelectionModel().getSelectedItem() != null) {
                    if (userGrid.getSelectionModel().getSelectedItems().size() > 1) {
                        MessageBox.alert(MessageBox.INFO, "Please select single item", null);
                    } else {
                        final CloudUserAdminServiceAsync service = (CloudUserAdminServiceAsync) Registry.get(CloudManager.USER_ADMIN_SERVICE);
                        Integer userId = ((CloudUserBean) userGrid.getSelectionModel().getSelectedItem()).getUserId();
                        service.getCloudUser(userId, new AsyncCallback<CloudUserBean>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                MessageBox.alert(MessageBox.ERROR, "Failed To Save ", null);
                            }

                            @Override
                            public void onSuccess(CloudUserBean cloudUserBean) {
                                labUserFormPanel.getFormBinding().bind(cloudUserBean);
                            }
                        });
                    }
                }
            }
        });
        return button;
    }


    private Button getDeleteButton() {

        Button button = new Button("Delete", new SelectionListener<ButtonEvent>() {
            public void componentSelected(ButtonEvent ce) {
                if (userGrid.getSelectionModel().getSelectedItems() != null && userGrid.getSelectionModel().getSelectedItems().size() > 0) {
                    final CloudUserAdminServiceAsync service = (CloudUserAdminServiceAsync) Registry.get(CloudManager.USER_ADMIN_SERVICE);
                    List<CloudUserBean> selectedItems = userGrid.getSelectionModel().getSelectedItems();
                    if (selectedItems != null && selectedItems.size() > 0) {
//                        service.terminateCloudResource(selectedItems, new AsyncCallback<Void>() {
//                            @Override
//                            public void onFailure(Throwable throwable) {
//                                MessageBox.alert(MessageBox.ERROR, "Failed to Delete instances", null);
//                            }
//
//                            @Override
//                            public void onSuccess(Void aVoid) {
//                                MessageBox.alert(MessageBox.INFO, "Successfully Deleted instances", null);
//                            }
//                        });
                    }
                }
            }
        });
        return button;
    }


    public ListStore<ModelData> getGridStore() {
        return gridStore;
    }

    private BaseListLoader<BaseListLoadResult<ModelData>> getLoader() {
        final CloudUserAdminServiceAsync service = (CloudUserAdminServiceAsync) Registry.get(CloudManager.USER_ADMIN_SERVICE);

        RpcProxy<List<CloudUserBean>> proxy = new RpcProxy<List<CloudUserBean>>() {
            @Override
            public void load(Object loadConfig,
                             AsyncCallback<List<CloudUserBean>> callback) {
                service.getCloudUsers(callback);
            }
        };
        final BaseListLoader<BaseListLoadResult<ModelData>> loader = new BaseListLoader<BaseListLoadResult<ModelData>>(proxy);
        return loader;
    }
}
